/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.upn.sigemfi.can.beans;

import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Administrador
 */
public abstract class AbstractController implements Serializable {

    public AbstractController() {
    }

    public static synchronized FacesContext getFacesContext() {
        return FacesContext.getCurrentInstance();
    }

    public static synchronized ExternalContext getExternalContext() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        return facesContext.getExternalContext();
    }

    public static synchronized Object getBean(String nombre) {
        FacesContext facesContext = getFacesContext();
        return facesContext.getApplication().getVariableResolver().resolveVariable(facesContext, nombre);
    }

    public static synchronized boolean isUserInRole(String role) {
        return getExternalContext().isUserInRole(role);
    }

    public boolean isLoggedIn() {
        return !getPrincipalName().isEmpty();
    }

    public static synchronized String getPrincipalName() {
        try {
            return getExternalContext().getUserPrincipal().getName();
        } catch (Exception e) {
            return "";
        }
    }

    public static synchronized HttpServletRequest getRequest() {
        ExternalContext ctx;
        try {
            ctx = getFacesContext().getExternalContext();
            return (HttpServletRequest) ctx.getRequest();
        } catch (Exception e) {
            return null;
        }
    }

    public static synchronized void error(String msg) {
        FacesContext facesContext = getFacesContext();
        HttpServletRequest reques;
        FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);
        facesContext.addMessage(null, facesMessage);
    }

    public static synchronized void warn(String msg) {
        FacesContext facesContext = getFacesContext();
        HttpServletRequest request;
        FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_WARN, msg, msg);
        facesContext.addMessage(null, facesMessage);
    }

    public static synchronized void info(String msg) {
        FacesContext facesContext = getFacesContext();
        HttpServletRequest request;
        FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg);
        facesContext.addMessage(null, facesMessage);
    }
}
